const { exec } = require('../db/mysql')

const getList = (author, keyword) => {
  let sql = `SELECT * FROM blogs WHERE 1=1` // 1=1 表示占位，防止没有条件下的语句报错
  if (author) {
    sql += ` AND author="${author}"`
  }
  if (keyword) {
    sql += ` AND title LIKE '%${keyword}%'`
  }
  sql += ` ORDER BY createtime DESC`

  return exec(sql)
}

const getDetail = id => {
  const sql = `SELECT * FROM blogs WHERE id=${id}`
  // return exec(sql).then(rows => {
  //   console.log(rows)
  //   return rows[0]
  // })
  // or
  return exec(sql)
}

const insertBlog = (blogData = {}) => {
  const { title, content, author } = blogData
  const createtime = Date.now()
  const sql = `INSERT blogs (title, content, createtime, author)
    VALUES ('${title}', '${content}', ${createtime}, '${author}')`
  return exec(sql).then(data => {
    return { id: data.insertId }
  })
}

/**
 * 修改一篇博客
 * @param {number} id
 * @param {object} blogData
 * @return {boolean}
 */
const updateBlog = (id, blogData = {}) => {
  const { title, content } = blogData
  const sql = `UPDATE blogs SET title='${title}', content='${content}' WHERE id=${id}`
  return exec(sql).then(data => {
    if (data.affectedRows > 0) {
      return true
    }
    return false
  })
}

/**
 * 删除一篇博客
 * @param {number} id
 * @return {boolean}
 */
const deleteBlog = (id, author) => {
  const sql = `UPDATE blogs SET status=0 WHERE id=${id} AND author='${author}'`
  return exec(sql).then(data => {
    if (data.affectedRows > 0) {
      return true
    }
    return false
  })
}

module.exports = {
  getList,
  getDetail,
  insertBlog,
  updateBlog,
  deleteBlog
}
